/**
 * InteractionManager - 交互管理器
 * 处理点击、拖拽等用户交互
 */

class InteractionManager {
  constructor(options = {}) {
    this.options = {
      width: options.width || 750,
      height: options.height || 1000,
      gridSize: options.gridSize || 80
    }
    
    this.camera = options.camera || { x: 0, y: 0, scale: 1 }
    this.isDragging = false
    this.dragStartPos = null
    this.dragTarget = null
    this.lastTapTime = 0
    this.tapTimeout = null
  }

  /**
   * 处理触摸开始
   */
  handleTouchStart(e, buildings, villagers) {
    const touch = this.getTouchPosition(e)
    if (!touch) return null
    
    this.isDragging = false
    this.dragStartPos = { ...touch }
    
    // 检测点击的对象
    const hitBuilding = this.hitTestBuilding(touch, buildings)
    const hitVillager = this.hitTestVillager(touch, villagers)
    
    if (hitBuilding) {
      this.dragTarget = { type: 'building', data: hitBuilding }
      return { type: 'building-touch-start', target: hitBuilding }
    } else if (hitVillager) {
      this.dragTarget = { type: 'villager', data: hitVillager }
      return { type: 'villager-touch-start', target: hitVillager }
    } else {
      this.dragTarget = { type: 'camera', data: null }
      return { type: 'camera-touch-start', position: touch }
    }
  }

  /**
   * 处理触摸移动
   */
  handleTouchMove(e) {
    const touch = this.getTouchPosition(e)
    if (!touch || !this.dragStartPos) return null
    
    const dx = touch.x - this.dragStartPos.x
    const dy = touch.y - this.dragStartPos.y
    const distance = Math.sqrt(dx * dx + dy * dy)
    
    // 移动超过10像素才算拖拽
    if (distance > 10) {
      this.isDragging = true
    }
    
    if (this.isDragging && this.dragTarget) {
      if (this.dragTarget.type === 'camera') {
        // 拖拽相机
        return {
          type: 'camera-drag',
          delta: { x: dx, y: dy }
        }
      } else if (this.dragTarget.type === 'building') {
        // 拖拽建筑
        const worldPos = this.screenToWorld(touch)
        return {
          type: 'building-drag',
          target: this.dragTarget.data,
          position: worldPos
        }
      }
    }
    
    return null
  }

  /**
   * 处理触摸结束
   */
  handleTouchEnd(e) {
    const touch = this.getTouchPosition(e)
    if (!touch) return null
    
    let result = null
    
    // 如果没有拖拽，则是点击
    if (!this.isDragging && this.dragTarget) {
      const now = Date.now()
      const isDoubleTap = (now - this.lastTapTime) < 300
      
      if (this.dragTarget.type === 'building') {
        result = {
          type: isDoubleTap ? 'building-double-tap' : 'building-tap',
          target: this.dragTarget.data
        }
      } else if (this.dragTarget.type === 'villager') {
        result = {
          type: isDoubleTap ? 'villager-double-tap' : 'villager-tap',
          target: this.dragTarget.data
        }
      } else {
        // 点击空地
        const worldPos = this.screenToWorld(touch)
        result = {
          type: 'empty-tap',
          position: worldPos,
          gridPosition: this.worldToGrid(worldPos)
        }
      }
      
      this.lastTapTime = now
    } else if (this.isDragging && this.dragTarget) {
      // 拖拽结束
      if (this.dragTarget.type === 'building') {
        const worldPos = this.screenToWorld(touch)
        result = {
          type: 'building-drop',
          target: this.dragTarget.data,
          position: worldPos,
          gridPosition: this.worldToGrid(worldPos)
        }
      }
    }
    
    // 重置状态
    this.isDragging = false
    this.dragStartPos = null
    this.dragTarget = null
    
    return result
  }

  /**
   * 处理长按
   */
  handleLongPress(e, buildings, villagers) {
    const touch = this.getTouchPosition(e)
    if (!touch) return null
    
    const hitBuilding = this.hitTestBuilding(touch, buildings)
    const hitVillager = this.hitTestVillager(touch, villagers)
    
    if (hitBuilding) {
      return { type: 'building-long-press', target: hitBuilding }
    } else if (hitVillager) {
      return { type: 'villager-long-press', target: hitVillager }
    } else {
      const worldPos = this.screenToWorld(touch)
      return {
        type: 'empty-long-press',
        position: worldPos,
        gridPosition: this.worldToGrid(worldPos)
      }
    }
  }

  /**
   * 获取触摸位置
   */
  getTouchPosition(e) {
    if (!e || !e.touches || e.touches.length === 0) return null
    
    const touch = e.touches[0]
    return {
      x: touch.x,
      y: touch.y
    }
  }

  /**
   * 建筑碰撞检测
   */
  hitTestBuilding(screenPos, buildings) {
    if (!buildings || buildings.length === 0) return null
    
    const worldPos = this.screenToWorld(screenPos)
    
    // 从后往前检测（后面的建筑在上层）
    for (let i = buildings.length - 1; i >= 0; i--) {
      const building = buildings[i]
      if (!building.position || !building.built) continue
      
      const bx = building.position.x
      const by = building.position.y
      const bw = 80 // 建筑宽度
      const bh = 80 // 建筑高度
      
      if (worldPos.x >= bx && worldPos.x <= bx + bw &&
          worldPos.y >= by && worldPos.y <= by + bh) {
        return building
      }
    }
    
    return null
  }

  /**
   * 村民碰撞检测
   */
  hitTestVillager(screenPos, villagers) {
    if (!villagers || villagers.length === 0) return null
    
    const worldPos = this.screenToWorld(screenPos)
    
    for (let i = villagers.length - 1; i >= 0; i--) {
      const villager = villagers[i]
      if (!villager.position) continue
      
      const vx = villager.position.x
      const vy = villager.position.y
      const radius = 20 // 村民半径
      
      const dx = worldPos.x - vx
      const dy = worldPos.y - vy
      const distance = Math.sqrt(dx * dx + dy * dy)
      
      if (distance <= radius) {
        return villager
      }
    }
    
    return null
  }

  /**
   * 屏幕坐标转世界坐标
   */
  screenToWorld(screenPos) {
    return {
      x: (screenPos.x - this.camera.x) / this.camera.scale,
      y: (screenPos.y - this.camera.y) / this.camera.scale
    }
  }

  /**
   * 世界坐标转屏幕坐标
   */
  worldToScreen(worldPos) {
    return {
      x: worldPos.x * this.camera.scale + this.camera.x,
      y: worldPos.y * this.camera.scale + this.camera.y
    }
  }

  /**
   * 世界坐标转网格坐标
   */
  worldToGrid(worldPos) {
    return {
      x: Math.floor(worldPos.x / this.options.gridSize),
      y: Math.floor(worldPos.y / this.options.gridSize)
    }
  }

  /**
   * 网格坐标转世界坐标
   */
  gridToWorld(gridPos) {
    return {
      x: gridPos.x * this.options.gridSize,
      y: gridPos.y * this.options.gridSize
    }
  }

  /**
   * 检查网格位置是否可用
   */
  isGridAvailable(gridPos, buildings, excludeBuilding = null) {
    if (!buildings) return true
    
    for (const building of buildings) {
      if (building === excludeBuilding) continue
      if (!building.position || !building.built) continue
      
      const buildingGrid = this.worldToGrid(building.position)
      
      // 检查是否重叠（假设建筑占1个网格）
      if (buildingGrid.x === gridPos.x && buildingGrid.y === gridPos.y) {
        return false
      }
    }
    
    return true
  }

  /**
   * 获取最近的可用网格
   */
  getNearestAvailableGrid(worldPos, buildings) {
    const targetGrid = this.worldToGrid(worldPos)
    
    // 如果目标位置可用，直接返回
    if (this.isGridAvailable(targetGrid, buildings)) {
      return targetGrid
    }
    
    // 螺旋搜索最近的可用网格
    for (let radius = 1; radius <= 5; radius++) {
      for (let dx = -radius; dx <= radius; dx++) {
        for (let dy = -radius; dy <= radius; dy++) {
          if (Math.abs(dx) !== radius && Math.abs(dy) !== radius) continue
          
          const checkGrid = {
            x: targetGrid.x + dx,
            y: targetGrid.y + dy
          }
          
          if (this.isGridAvailable(checkGrid, buildings)) {
            return checkGrid
          }
        }
      }
    }
    
    return targetGrid
  }

  /**
   * 更新相机
   */
  updateCamera(camera) {
    this.camera = camera
  }
}

export default InteractionManager
